package com.xinghen.security.core.validate.code;

import com.xinghen.security.core.SecurityConstants;
import com.xinghen.security.core.SecurityResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xinghen
 * @ClassName: ValidateCodeController
 * @Package: com.xinghen.security.core.validate.code
 * @Description 生成校验码的请求处理器
 * @create 2018-04-18 15:02
 */
@RestController
@Slf4j
public class ValidateCodeController {

    @Autowired
    private ValidateCodeProcessorManager validateCodeProcessorManager;

    /**
     * 创建验证码
     *
     * @param request
     * @param response
     * @param type
     * @throws Exception
     */
    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
    public void createValidateCode(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable String type) throws Exception {
        validateCodeProcessorManager.findValidateCodeProcessor(type)
                .create(new ServletWebRequest(request, response));
    }

    /**
     * 校验验证码
     *
     * @param request
     * @param response
     * @param type
     * @return
     */
    @PostMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
    public Object checkCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) {
        SecurityResult result = new SecurityResult(SecurityResult.SUCCESS_CODE, "校验成功", true);
        try {
            validateCodeProcessorManager.findValidateCodeProcessor(type).check(new ServletWebRequest(request, response));
        } catch (ValidateCodeException e) {
            result = SecurityResult.error(e.getMessage(), false);
        } catch (Exception e) {
            log.error("getAccessToken={}", e.getMessage(), e);
            result = SecurityResult.error("验证码错误", false);
        }
        return result;
    }

}
